/**
 * DJI无人机监控系统前端JavaScript
 */

// 全局变量
let map;
let droneMarkers = {};
let selectedDroneId = null;
let missionPolyline = null;
let waypointMarkers = [];
let isCreatingMission = false;
let newMissionWaypoints = [];

// 初始化地图
function initMap() {
    map = L.map('map').setView([31.2304, 121.4737], 15);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    
    // 地图点击事件，用于添加航点
    map.on('click', function(e) {
        if (isCreatingMission && selectedDroneId) {
            addWaypointToMission(e.latlng.lat, e.latlng.lng);
        }
    });
}

// 加载无人机列表
function loadDroneList() {
    fetch('drone/json')
        .then(response => response.json())
        .then(drones => {
            const droneListElement = document.getElementById('droneList');
            droneListElement.innerHTML = '';
            
            drones.forEach(drone => {
                // 创建无人机列表项
                const droneItem = document.createElement('a');
                droneItem.className = 'list-group-item list-group-item-action drone-card';
                droneItem.setAttribute('data-drone-id', drone.id);
                
                // 设置状态徽章的颜色
                let statusClass = 'bg-secondary';
                if (drone.status === 'FLYING') statusClass = 'bg-success';
                if (drone.status === 'RETURNING') statusClass = 'bg-info';
                if (drone.status === 'LANDING') statusClass = 'bg-warning';
                
                droneItem.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="mb-1">${drone.model}</h6>
                        <span class="badge ${statusClass} status-badge">${drone.status}</span>
                    </div>
                    <div class="mb-1">
                        <small>电池: ${drone.batteryLevel.toFixed(1)}%</small>
                        <div class="progress battery-indicator">
                            <div class="progress-bar ${getBatteryColorClass(drone.batteryLevel)}" 
                                 style="width: ${drone.batteryLevel}%"></div>
                        </div>
                    </div>
                `;
                
                // 点击事件
                droneItem.addEventListener('click', function() {
                    selectDrone(drone.id);
                });
                
                droneListElement.appendChild(droneItem);
                
                // 添加或更新地图上的无人机标记
                updateDroneMarker(drone);
            });
            
            // 如果有选中的无人机，更新其信息
            if (selectedDroneId) {
                updateSelectedDroneInfo();
            }
        })
        .catch(error => console.error('加载无人机列表失败:', error));
}

// 更新无人机标记
function updateDroneMarker(drone) {
    // 如果标记已存在，更新位置
    if (droneMarkers[drone.id]) {
        droneMarkers[drone.id].setLatLng([drone.latitude, drone.longitude]);
    } else {
        // 创建新标记
        const droneIcon = L.divIcon({
            className: 'drone-icon',
            html: '<i class="fas fa-drone-alt" style="font-size: 24px; color: #007bff;"></i>',
            iconSize: [24, 24],
            iconAnchor: [12, 12]
        });
        
        // 使用简单圆形代替图标（因为可能没有Font Awesome）
        const marker = L.circleMarker([drone.latitude, drone.longitude], {
            radius: 8,
            fillColor: '#007bff',
            color: '#fff',
            weight: 2,
            opacity: 1,
            fillOpacity: 0.8
        });
        
        marker.bindPopup(`
            <strong>${drone.model}</strong><br>
            状态: ${drone.status}<br>
            电池: ${drone.batteryLevel.toFixed(1)}%<br>
            高度: ${drone.altitude.toFixed(1)}m<br>
            速度: ${drone.speed.toFixed(1)}m/s
        `);
        
        marker.addTo(map);
        droneMarkers[drone.id] = marker;
    }
}

// 选择无人机
function selectDrone(droneId) {
    selectedDroneId = droneId;
    
    // 高亮选中的无人机列表项
    document.querySelectorAll('.drone-card').forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('data-drone-id') === droneId) {
            item.classList.add('active');
        }
    });
    
    // 显示控制面板
    document.getElementById('droneControlPanel').style.display = 'block';
    document.getElementById('missionPanel').style.display = 'block';
    
    // 更新无人机信息
    updateSelectedDroneInfo();
    
    // 聚焦地图到选中的无人机
    if (droneMarkers[droneId]) {
        map.setView(droneMarkers[droneId].getLatLng(), 16);
        droneMarkers[droneId].openPopup();
    }
}

// 更新选中无人机的信息
function updateSelectedDroneInfo() {
    if (!selectedDroneId) return;
    
    fetch(`api/drone-data?droneId=${selectedDroneId}`)
        .then(response => response.json())
        .then(drone => {
            const droneInfoElement = document.getElementById('droneInfo');
            
            // 设置状态徽章的颜色
            let statusClass = 'bg-secondary';
            if (drone.status === 'FLYING') statusClass = 'bg-success';
            if (drone.status === 'RETURNING') statusClass = 'bg-info';
            if (drone.status === 'LANDING') statusClass = 'bg-warning';
            
            droneInfoElement.innerHTML = `
                <h5 class="card-title">${drone.model}</h5>
                <p class="mb-1">ID: ${drone.id}</p>
                <p class="mb-1">状态: <span class="badge ${statusClass}">${drone.status}</span></p>
                <p class="mb-1">电池电量: ${drone.batteryLevel.toFixed(1)}%</p>
                <div class="progress mb-3">
                    <div class="progress-bar ${getBatteryColorClass(drone.batteryLevel)}" 
                         style="width: ${drone.batteryLevel}%"></div>
                </div>
                <p class="mb-1">高度: ${drone.altitude.toFixed(1)} 米</p>
                <p class="mb-1">速度: ${drone.speed.toFixed(1)} m/s</p>
                <p class="mb-1">坐标: ${drone.latitude.toFixed(6)}, ${drone.longitude.toFixed(6)}</p>
            `;
            
            // 更新地图上的无人机标记
            updateDroneMarker(drone);
        })
        .catch(error => console.error('获取无人机信息失败:', error));
}

// 根据电池电量获取颜色类
function getBatteryColorClass(batteryLevel) {
    if (batteryLevel > 70) return 'bg-success';
    if (batteryLevel > 30) return 'bg-warning';
    return 'bg-danger';
}

// 发送无人机控制命令
function sendDroneCommand(action) {
    if (!selectedDroneId) return;
    
    const formData = new FormData();
    formData.append('droneId', selectedDroneId);
    formData.append('action', action);
    
    fetch('drone/control', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('命令发送成功:', data);
        // 立即更新无人机信息
        updateSelectedDroneInfo();
    })
    .catch(error => console.error('命令发送失败:', error));
}

// 开始创建任务
function startCreateMission() {
    if (!selectedDroneId) {
        alert('请先选择一架无人机');
        return;
    }
    
    isCreatingMission = true;
    newMissionWaypoints = [];
    
    // 清除之前的航点标记
    clearWaypointMarkers();
    
    // 显示创建任务模态框
    const modal = new bootstrap.Modal(document.getElementById('createMissionModal'));
    modal.show();
    
    // 更新航点列表
    updateWaypointsList();
}

// 添加航点到任务
function addWaypointToMission(lat, lng) {
    // 默认高度为50米
    const altitude = 50;
    
    // 添加到航点列表
    newMissionWaypoints.push({
        latitude: lat,
        longitude: lng,
        altitude: altitude,
        action: 'HOVER',
        hoverTime: 0
    });
    
    // 在地图上添加标记
    const marker = L.marker([lat, lng], {
        icon: L.divIcon({
            className: 'waypoint-icon',
            html: `<div style="background-color: #dc3545; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;">${newMissionWaypoints.length}</div>`,
            iconSize: [12, 12],
            iconAnchor: [6, 6]
        })
    });
    
    marker.addTo(map);
    waypointMarkers.push(marker);
    
    // 如果有多个航点，绘制路径
    if (newMissionWaypoints.length > 1) {
        drawMissionPath();
    }
    
    // 更新航点列表
    updateWaypointsList();
}

// 绘制任务路径
function drawMissionPath() {
    // 清除之前的路径
    if (missionPolyline) {
        map.removeLayer(missionPolyline);
    }
    
    // 创建路径点数组
    const pathPoints = newMissionWaypoints.map(wp => [wp.latitude, wp.longitude]);
    
    // 创建新路径
    missionPolyline = L.polyline(pathPoints, {
        color: '#dc3545',
        weight: 3,
        opacity: 0.7,
        dashArray: '5, 10'
    }).addTo(map);
}

// 清除航点标记
function clearWaypointMarkers() {
    // 清除地图上的标记
    waypointMarkers.forEach(marker => map.removeLayer(marker));
    waypointMarkers = [];
    
    // 清除路径
    if (missionPolyline) {
        map.removeLayer(missionPolyline);
        missionPolyline = null;
    }
}

// 更新航点列表显示
function updateWaypointsList() {
    const waypointsListElement = document.getElementById('waypointsList');
    
    if (newMissionWaypoints.length === 0) {
        waypointsListElement.innerHTML = '<p class="text-muted">在地图上点击添加航点</p>';
        return;
    }
    
    let html = '<ul class="list-group">';
    
    newMissionWaypoints.forEach((waypoint, index) => {
        html += `
            <li class="list-group-item d-flex justify-content-between align-items-center">
                <div>
                    <strong>航点 ${index + 1}</strong><br>
                    <small>坐标: ${waypoint.latitude.toFixed(6)}, ${waypoint.longitude.toFixed(6)}</small><br>
                    <small>高度: ${waypoint.altitude}米</small>
                </div>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeWaypoint(${index})">删除</button>
            </li>
        `;
    });
    
    html += '</ul>';
    waypointsListElement.innerHTML = html;
}

// 删除航点
function removeWaypoint(index) {
    // 从数组中移除
    newMissionWaypoints.splice(index, 1);
    
    // 清除所有标记并重新绘制
    clearWaypointMarkers();
    
    // 重新添加所有航点标记
    newMissionWaypoints.forEach((wp, i) => {
        const marker = L.marker([wp.latitude, wp.longitude], {
            icon: L.divIcon({
                className: 'waypoint-icon',
                html: `<div style="background-color: #dc3545; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;">${i+1}</div>`,
                iconSize: [12, 12],
                iconAnchor: [6, 6]
            })
        });
        
        marker.addTo(map);
        waypointMarkers.push(marker);
    });
    
    // 如果有多个航点，重新绘制路径
    if (newMissionWaypoints.length > 1) {
        drawMissionPath();
    }
    
    // 更新航点列表
    updateWaypointsList();
}

// 保存任务
function saveMission() {
    if (!selectedDroneId || newMissionWaypoints.length === 0) {
        alert('请选择无人机并添加至少一个航点');
        return;
    }
    
    const missionName = document.getElementById('missionName').value;
    if (!missionName) {
        alert('请输入任务名称');
        return;
    }
    
    // 准备任务数据
    const missionData = {
        action: 'create',
        name: missionName,
        droneId: selectedDroneId,
        waypoints: newMissionWaypoints
    };
    
    // 发送创建任务请求
    fetch('api/mission', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(missionData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('任务创建成功:', data);
        alert('任务创建成功!');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('createMissionModal'));
        modal.hide();
        
        // 重置状态
        isCreatingMission = false;
        newMissionWaypoints = [];
        clearWaypointMarkers();
    })
    .catch(error => console.error('任务创建失败:', error));
}

// 加载任务列表
function loadMissionsList() {
    if (!selectedDroneId) return;
    
    fetch(`api/mission?droneId=${selectedDroneId}`)
        .then(response => response.json())
        .then(missions => {
            const missionsListElement = document.getElementById('missionsList');
            
            if (missions.length === 0) {
                missionsListElement.innerHTML = '<p class="text-center text-muted">暂无任务</p>';
                return;
            }
            
            let html = '<div class="list-group">';
            
            missions.forEach(mission => {
                // 设置状态徽章的颜色
                let statusClass = 'bg-secondary';
                if (mission.status === 'EXECUTING') statusClass = 'bg-success';
                if (mission.status === 'COMPLETED') statusClass = 'bg-info';
                if (mission.status === 'ABORTED') statusClass = 'bg-danger';
                
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-1">${mission.name}</h6>
                            <span class="badge ${statusClass}">${mission.status}</span>
                        </div>
                        <p class="mb-1">航点数量: ${mission.waypoints.length}</p>
                        <div class="d-flex justify-content-between mt-2">
                            <button class="btn btn-sm btn-primary" onclick="viewMission('${mission.id}')">查看</button>
                            <button class="btn btn-sm btn-success" onclick="executeMission('${mission.id}')"
                                ${mission.status === 'EXECUTING' ? 'disabled' : ''}>执行</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteMission('${mission.id}')">删除</button>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            missionsListElement.innerHTML = html;
        })
        .catch(error => console.error('加载任务列表失败:', error));
}

// 查看任务详情
function viewMission(missionId) {
    fetch(`api/mission?missionId=${missionId}`)
        .then(response => response.json())
        .then(mission => {
            // 清除之前的航点标记
            clearWaypointMarkers();
            
            // 添加航点标记
            mission.waypoints.forEach((waypoint, index) => {
                const marker = L.marker([waypoint.latitude, waypoint.longitude], {
                    icon: L.divIcon({
                        className: 'waypoint-icon',
                        html: `<div style="background-color: #0d6efd; width: 12px; height: 12px; border-radius: 50%; border: 2px solid white;">${index+1}</div>`,
                        iconSize: [12, 12],
                        iconAnchor: [6, 6]
                    })
                });
                
                marker.bindPopup(`
                    <strong>航点 ${index + 1}</strong><br>
                    坐标: ${waypoint.latitude.toFixed(6)}, ${waypoint.longitude.toFixed(6)}<br>
                    高度: ${waypoint.altitude}米<br>
                    动作: ${waypoint.action}<br>
                    悬停时间: ${waypoint.hoverTime}秒
                `);
                
                marker.addTo(map);
                waypointMarkers.push(marker);
            });
            
            // 绘制路径
            if (mission.waypoints.length > 1) {
                const pathPoints = mission.waypoints.map(wp => [wp.latitude, wp.longitude]);
                
                missionPolyline = L.polyline(pathPoints, {
                    color: '#0d6efd',
                    weight: 3,
                    opacity: 0.7
                }).addTo(map);
            }
            
            // 调整地图视图以显示所有航点
            if (mission.waypoints.length > 0) {
                const bounds = L.latLngBounds(mission.waypoints.map(wp => [wp.latitude, wp.longitude]));
                map.fitBounds(bounds.pad(0.1));
            }
            
            // 关闭任务列表模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('missionsListModal'));
            modal.hide();
        })
        .catch(error => console.error('获取任务详情失败:', error));
}

// 执行任务
function executeMission(missionId) {
    const missionData = {
        action: 'execute',
        missionId: missionId
    };
    
    fetch('api/mission', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(missionData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('任务执行成功:', data);
        alert('任务开始执行!');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('missionsListModal'));
        modal.hide();
        
        // 立即更新无人机信息
        updateSelectedDroneInfo();
    })
    .catch(error => console.error('任务执行失败:', error));
}

// 删除任务
function deleteMission(missionId) {
    if (!confirm('确定要删除此任务吗？')) return;
    
    fetch(`api/mission?missionId=${missionId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        console.log('任务删除成功:', data);
        alert('任务已删除!');
        
        // 重新加载任务列表
        loadMissionsList();
    })
    .catch(error => console.error('任务删除失败:', error));
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化地图
    initMap();
    
    // 加载无人机列表
    loadDroneList();
    
    // 设置定时刷新
    setInterval(loadDroneList, 3000);
    setInterval(function() {
        if (selectedDroneId) {
            updateSelectedDroneInfo();
        }
    }, 1000);
    
    // 绑定控制按钮事件
    document.getElementById('takeoffBtn').addEventListener('click', function() {
        sendDroneCommand('takeoff');
    });
    
    document.getElementById('landBtn').addEventListener('click', function() {
        sendDroneCommand('land');
    });
    
    document.getElementById('returnBtn').addEventListener('click', function() {
        sendDroneCommand('return');
    });
    
    document.getElementById('hoverBtn').addEventListener('click', function() {
        sendDroneCommand('hover');
    });
    
    // 绑定任务按钮事件
    document.getElementById('createMissionBtn').addEventListener('click', function() {
        startCreateMission();
    });
    
    document.getElementById('viewMissionsBtn').addEventListener('click', function() {
        loadMissionsList();
        const modal = new bootstrap.Modal(document.getElementById('missionsListModal'));
        modal.show();
    });
    
    document.getElementById('saveMissionBtn').addEventListener('click', function() {
        saveMission();
    });
});